package parser

import (
	"fmt"
	"github.com/fatih/color"
	"github.com/hashicorp/hcl/v2"
	"github.com/ihaiker/tfwrapper/internal/config"
	"github.com/ihaiker/tfwrapper/internal/errors"
	"github.com/ihaiker/tfwrapper/internal/eval"
	"github.com/ihaiker/tfwrapper/internal/logger"
	"github.com/zclconf/go-cty/cty"
)

func evaluateLocalsBlock(options config.Running, file *hcl.File) (map[string]cty.Value, hcl.Diagnostics) {
	log := logger.Logger(options, "locals")

	content, _, diags := file.Body.PartialContent(&hcl.BodySchema{
		Blocks: []hcl.BlockHeaderSchema{
			{Type: "locals"},
		},
	})
	if diags.HasErrors() || len(content.Blocks) == 0 {
		return nil, diags
	}

	if len(content.Blocks) > 1 {
		return nil, diags.Append(&hcl.Diagnostic{
			Severity: hcl.DiagError,
			Summary:  "locals block must be unique",
			Detail:   fmt.Sprintf("locals block must be unique, but found %d", len(content.Blocks)),
			Context:  &content.Blocks[1].DefRange,
		})
	}

	wec, diags := eval.CreateEvalContext(options)
	if diags.HasErrors() {
		return nil, diags
	}

	locals := make(map[string]cty.Value, 0)
	for i := MaxIterations; i >= 0; i-- {
		locals, diags = wec.DecodeBlockAttributes(content.Blocks[0])
		if !diags.HasErrors() {
			break
		}
		if diags.HasErrors() && errors.NotOnlyUnsupportedAttribute(diags) {
			return locals, diags
		}
		wec.AppendLocals(locals)
	}

	for key, _ := range locals {
		log.Debugf("Use defined local %s", color.HiMagentaString(key))
	}
	return locals, nil
}
